package andy.demo.json;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.LinkedList;

import com.google.gson.stream.JsonReader;

public class JsonUtils {
	
	public static String single_jsonData = "{\"name\":\"lucy\",\"age\"20}";
	public static String muti_jsonData = "[{\"name\":\"andy\",\"age\"23},{\"name\":\"lucy\",\"age\"20}]";
	
	public static void parseMutiJson(String jsonData) {
		
		try {
			JsonReader jsonReader = new JsonReader(new StringReader(jsonData));
			jsonReader.beginArray();
			while (jsonReader.hasNext()) {
				jsonReader.beginObject();
				while(jsonReader.hasNext()){
					 String tagName = jsonReader.nextName();
					 if("name".equals(tagName)){
						 System.out.println("name=" + jsonReader.nextString());
					 }else if("age".equals(tagName)) {
						 System.out.println("age=" + jsonReader.nextInt());
					 }
				}
				jsonReader.endObject(); 
			}
			jsonReader.endArray();
		} catch (IOException e) {
			System.out.println("failed to parseMutiJason");
		}
	}
	
//	public static void parseSingleJsonToObject(String singleJsonData) {
//		Gson gson = new Gson();
//		User user = gson.fromJson(singleJsonData, User.class);
//		System.out.println("user:" + user.toString());
//	}
//	public static void parseMutiJsonToObject(String mutiJsonData) {
//		Type listType = new TypeToken<LinkedList<User>>(){}.getType();
//		Gson gson = new Gson();
//		LinkedList<User> userList = gson.fromJson(mutiJsonData, listType);
//		
//		for (Iterator iterator = userList.iterator(); iterator.hasNext();) {
//			User user = (User) iterator.next();
//			System.out.println("user:" + user);
//			
//		}
//	}

}
